package br.usp.icmc.biomac.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Babu Hussain
 * @version 0.5
 * 
 */
public class DicomRetrieve2 extends HttpServlet {
	/**
	 * 
	 */
//	private String server = "127.0.0.1";
	private String server = "biomac.icmc.usp.br";
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String patientName = request.getParameter("patientName");
		String patientId = request.getParameter("patientId");
		String accessionNum = request.getParameter("accessionNum");
		String examType = request.getParameter("examType");
		String studyDate = request.getParameter("studyDate");
		String studyUID = request.getParameter("studyUID");
		String url = "";
		if (patientName != null){
			url = "http://" + server + ":8325/search/?patientName="+patientName;
		} else if (patientId != null){
				url = "http://" + server + ":8325/search/?patientId="+patientId;
		} else if (accessionNum != null){
				url = "http://" + server + ":8325/search/?accessionNum="+accessionNum;
		} else if (examType != null){
				url = "http://" + server + ":8325/search/?examType="+examType;
		} else if (studyDate != null){
				url = "http://" + server + ":8325/search/?studyDate="+studyDate;
		} else {
			url = "http://" + server + ":8325/search/?searchtype=series&studyUID="+studyUID;
		}
		
		InputStream resultInStream = null;
		OutputStream out = response.getOutputStream();
		try {
			int bytes_read;
			URL imageUrl = new URL(url);
			resultInStream = imageUrl.openStream();
			byte[] buffer = new byte[4096];
			while ((bytes_read = resultInStream.read(buffer)) != -1)
				out.write(buffer, 0, bytes_read);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}